package org.yscz.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.yscz.common.Constants;
import org.yscz.common.HttpStatus;
import org.yscz.common.Result;
import org.yscz.common.enums.MediaResponseEnum;
import org.yscz.entity.RoomBean;
import org.yscz.entity.vo.FaceVo;
import org.yscz.exception.MediaCommandException;
import org.yscz.mqtt.MqttCustomClient;
import org.yscz.service.EvaluationService;
import org.yscz.media.MediaService;


import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author achen
 * @create 2021-08-23 9:50
 */
@RestController
@Slf4j
@Api("人脸识别接口")
public class FaceController {

    public static Map map = new HashMap();

    private static Boolean flagStart = true;

    private static Boolean flagRecognition = true;

    /**
     * 流媒体开启时的第一次的uuid
     */
    private static String uuidStart = "";

    /**
     * 人脸识别时的第一次的uuid
     */
    private static String uuidRecognition = "";

    @Autowired
    private EvaluationService evaluationService;

    @Autowired
    private MqttCustomClient mqttCustomClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MediaService mediaService;

    @Value("${yscz.mediaServer.ip}")
    private String mediaIp;

    @Value("${yscz.mediaServer.flv-port}")
    private Integer flvPort;

    @Value("${yscz.usbDevice.cameraUrl}")
    private String cameraUrl;

    @Value("${yscz.usbDevice.enable:true}")
    private boolean usbEnable;

    @PostMapping("/face/startFaceRecognitionControl")
    @ApiOperation(value = "人脸识别开启接口", httpMethod = "POST")
    public Result<JSONObject> startFaceRecognitionControl(@RequestBody JSONObject jObj) {
        //uuid
        String uuid = UUID.randomUUID().toString();
        map.put("uuid", uuid);

        //流媒体地址
        RoomBean roomBean = new RoomBean().setCameraUrl(cameraUrl).setUuid(uuid);

        //打开摄像头，保存流媒体开始的uuid
        /*StringBuilder key = new StringBuilder();
        if (flagStart) {
            long currentTime = System.currentTimeMillis();

            //人脸识别开始
            key.append(currentTime);
            key.append("_");
            key.append(uuid);

            uuidStart = key.toString();

            flagStart = false;
        }*/

        //调用流媒体接口添加视频流
        evaluationService.startEvaluation(roomBean, false);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("uuid", uuid);
        jsonObject.put("cameraUrl", flvMethod(uuid, mediaIp, flvPort));

        new Thread(() -> {
            this.faceStartRecognition(jObj);
        }).start();

        return Result.success(HttpStatus.SUCCESS, "人脸识别开始", jsonObject);
    }

    @PostMapping("/face/faceRecognition")
    @ApiOperation(value = "人脸识别接口", httpMethod = "POST")
    public Result faceRecognitionControl(@RequestBody JSONObject jObj) {
        //人脸识别的uuid开始与结束要保持一致
        //String uuid = UUID.randomUUID().toString();

        //第一次人脸识别，保存uuid
        /*StringBuilder key = new StringBuilder();
        if (flagRecognition) {
            long currentTime = System.currentTimeMillis();

            //人脸识别开始
            key.append(currentTime);
            key.append("_");
            key.append(uuid);

            //将currentTime+uuid拼接为key
            uuidRecognition = key.toString();

            flagRecognition = false;
        }*/

        JSONObject jsonObject = new JSONObject();
        String jsonFace = null;
        jsonObject.put("url", cameraUrl);
        jsonObject.put("state", jObj.get("state"));
        //人脸识别没有结束
        if ((Boolean) jObj.get("state")) {
            jsonObject.put("uid", "1234");
            jsonFace = JSONObject.toJSONString(jsonObject);

            //mqtt通知算法人脸识别开始
            mqttCustomClient.publish(Constants.FACE_RECOGNITION_CONTROL, jsonFace);
        } else {
            //如果传过来的state为false，说明人脸识别结束，关闭流媒体，通知算法结束
            /*flagStart = true;
            flagRecognition = true;*/

            //关闭流媒体
            mediaService.delSteam((String) map.get("uuid"));
            mediaService.stopUsbStream();

            //通知算法结束
            jsonObject.put("uid", uuidRecognition);
            jsonFace = JSONObject.toJSONString(jsonObject);

            //通知算法人脸识别结束
            mqttCustomClient.publish(Constants.FACE_RECOGNITION_CONTROL, jsonFace);
        }

        return Result.success(HttpStatus.SUCCESS, "人脸识别进行中");
    }

    /**
     * 转换rtsp为flv
     *
     * @param uuid
     */
    public static String flvMethod(String uuid, String mediaIp, Integer flvPort) {
        //cameraUrl:http://192.168.16.166:7070/live/e8b7f55e-f075-4b60-95a7-e48fbcee86bb.flv 前台需要根据.flv播放视频
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("http://");
        stringBuilder.append(mediaIp);
        stringBuilder.append(":");
        stringBuilder.append(flvPort);
        stringBuilder.append("/live/");
        stringBuilder.append(uuid);
        stringBuilder.append(".flv");
        return stringBuilder.toString();
    }

    public void faceStartRecognition(JSONObject jObj) {
        //人脸识别的uuid开始与结束要保持一致
        //String uuid = UUID.randomUUID().toString();

        //第一次人脸识别，保存uuid
        /*StringBuilder key = new StringBuilder();
        if (flagRecognition) {
            long currentTime = System.currentTimeMillis();

            //人脸识别开始
            key.append(currentTime);
            key.append("_");
            key.append(uuid);

            //将currentTime+uuid拼接为key
            uuidRecognition = key.toString();

            flagRecognition = false;
        }*/

        JSONObject jsonObject = new JSONObject();
        String jsonFace = null;
        jsonObject.put("url", cameraUrl);
        jsonObject.put("state", jObj.get("state"));
        //人脸识别没有结束
        if ((Boolean) jObj.get("state")) {
            jsonObject.put("uid", "1234");
            jsonFace = JSONObject.toJSONString(jsonObject);

            //mqtt通知算法人脸识别开始
            mqttCustomClient.publish(Constants.FACE_RECOGNITION_CONTROL, jsonFace);
        } else {
            //如果传过来的state为false，说明人脸识别结束，关闭流媒体，通知算法结束
            //flagStart = true;
            //flagRecognition = true;

            //关闭流媒体
            mediaService.delSteam((String)map.get("uuid"));
            mediaService.stopUsbStream();

            //通知算法结束
            jsonObject.put("uid", "1234");
            jsonFace = JSONObject.toJSONString(jsonObject);

            //通知算法人脸识别结束
            mqttCustomClient.publish(Constants.FACE_RECOGNITION_CONTROL, jsonFace);
        }
    }
}
